import DatePicker from "components/antd-compatible/date-picker";
import React from 'react'
import {connect} from 'react-redux'
import {checkMenuDisabled, deepFullCopy, messages, queryCurrencyPrecision} from "share/common";
import {Button, Input, Select, Form, Row, Col, Icon, Spin, InputNumber,  message} from 'antd';
import corporatePaymentReportService from 'containers/corporate-payment-report/corporate-payment-report.service';

import Chooser from "components/chooser";
import Condition from 'components/condition'
import errorMessage from "share/errorMessage";
import moment from "moment";
import WrapFormItem from "components/wrap-form-item";
import 'styles/corporate-payment-report/pay-info-detail.scss'
import PayInfoCustomFields from "../component/pay-info-custom-fields";
import AssociateContract from "./associate-contract";
import AddBankAccount from "../component/add-bank-account";
import { validation } from '../component/validation'

const FormItem = Form.Item;
const {TextArea} = Input;
const Option = Select.Option;
const {If, Else} = Condition;

class PayWithInvoice extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      payInfoDetail: {},
      editMode: false,
      bankListOption: [],
      prepaymentApplyColumns: [
        {
          title: messages('finance-9.key8')/*对公支付单号*/,
          dataIndex: 'businessCode',
          width: 150
        }, {
          title: messages('common.currency')/*币种*/,
          dataIndex: 'currencyCode',
          width: 80
        }, {
          title: messages('finance-9.key9')/*核销金额*/,
          dataIndex: 'writeOffAmount',
          render: (value, record) => this.filterMoney(value, queryCurrencyPrecision(record.currencyCode)),
          width: 200
        }
      ],
      paymentMethodList: [],
      prePaymentList: [],
      show: false,
      contract: [],
      vendorInfo: {}
    };
  }

  componentWillMount() {
    const { paymentScheduleId, payInfoDetail } = this.props;
    let promiseList = [
      this.getBankList(), this.handleGetPaymentMethod(), this.getPrePaymentList()
    ];
    paymentScheduleId && promiseList.push(this.getPayInfoDetail(paymentScheduleId));
    this.setState({ loading: true });
    Promise.all(promiseList).then(res => {
      let bankInfo = res[0].data || {};
      this.setState({
        loading: false,
        bankListOption: bankInfo.venBankAccountBeans,
        vendorInfo: {
          id: bankInfo.id,
          venNickname: bankInfo.venNickname,
          venderCode: bankInfo.venderCode,
          source: bankInfo.source,
          venderTypeId: bankInfo.venderTypeId,
          venderTypeName: bankInfo.venderTypeName,
        },
        paymentMethodList: res[1] ? res[1].data : [],
        prePaymentList: res[2] ? res[2].data : [],
        payInfoDetail: res[3] ? res[3].data : {},
        contract: res[3] ? res[3].data.contractAssociatedDTOList : [],
        contractLineId:  (res[3] && res[3].data.contractAssociatedDTOList && res[3].data.contractAssociatedDTOList[0]) ?
          res[3].data.contractAssociatedDTOList[0].contractLineId : ''
      }, () => {
        !paymentScheduleId && payInfoDetail &&
        this.props.form.setFieldsValue({ prepaymentTypeId: payInfoDetail.prepaymentTypeId });
      });
    }).catch(e => {
      console.log(e);
      this.setState({ loading: false });
      errorMessage(e.response);
    });
  };

  getPrePaymentList = async () => {
    const { expenseInfo: { setOfBooksId, formOID } } = this.props;
    let params = { formOID };
    return corporatePaymentReportService.getPrePaymentList(setOfBooksId, params)
  };

  getPayInfoDetail = async paymentScheduleId => {
    return corporatePaymentReportService.getPayingInfoWithNoInvoiceDetail(paymentScheduleId)
  };

  handleGetPaymentMethod = async () => {
    const { tenant: { tenantId }} = this.props;
    return corporatePaymentReportService.getApplicationPaymentMethod(tenantId)
  };

  getBankList = async () => {
    const { expenseInfo } = this.props;
    let params = {
      vendorInfoId: expenseInfo.corpSupplierId,
      status: 1001
    };
    return corporatePaymentReportService.getBanks(params);
  };

  handleSubmit = (e) => {
    const { payInfoDetail } = this.state;
    const { expenseInfo, operateMode } = this.props;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        let params = {
          paymentScheduleType: 1003, //预付行
          prepaymentHeadId: expenseInfo.id, //单据id
          prepaymentTypeId: values.prepaymentTypeId,
          amount: values.planedAmount.planedAmount,//原币金额
          remark: values.remark,
          currencyCode: expenseInfo.currencyCode,
          baseCurrencyCode: expenseInfo.baseCurrencyCode,
          payeeId: expenseInfo.corpSupplierId,
          payeeType: 1001,
          planedPaymentDate: values.planedPaymentDate,
          payeeAccountNumber: values.accountNumber,
          paymentMethodId: values.paymentMethodId,
          status: expenseInfo.status,
          contractHeaderId: expenseInfo.contractHeaderId,
          contractAssociatedDTOList: payInfoDetail.contractAssociatedDTOList
        };
        operateMode === 'EDIT' && (params = Object.assign({}, params, {
          id: payInfoDetail.id,
          prepaymentLineOid: payInfoDetail.prepaymentLineOid
        }));

        validation(params).then(() => {
          this.setState({ loading: true });
          corporatePaymentReportService.savePayInfoWithNoInvoiceDetail(params).then(res => {
            this.setState({ loading: false });
            this.props.close(true);
          }).catch(e => {
            this.setState({ loading: false });
            errorMessage(e.response)
          });
        }).catch(errorMessages => {
          if (errorMessages[0]) {
            errorMessages.length === 1 ? message.error(errorMessages) :
              message.error(errorMessages.map((item, index) => {
                return (<p style={{textAlign: 'left', margin: '5px 0 0'}}>{index + 1}: {item} </p>)
              }));
          }
        })
      }
    })
  };

  onChangeBankAccount = value => {
    const { bankListOption } = this.state;
    let selectedAccount = bankListOption.filter(i => i.bankAccount === value)[0];
    this.props.form.setFieldsValue({ accountName: selectedAccount.venBankNumberName });
  };

  onChangeContractLine = contract => {
    let { contractLineId, payInfoDetail } = this.state;
    //没有更改选择项时，不需要走下面的逻辑
    if (contract[0] && contract[0].contractLineId === contractLineId) { return; }
    contract[0] && contract.map(i => i.lineAvailableAmount = i.lineAvailableAmount || 0);
    this.setState({
      contractLineId: contract[0] && contract[0].contractLineId,
      payInfoDetail: Object.assign({}, payInfoDetail, { contractAssociatedDTOList: contract }),
      contract
    })
  };

  onChangePaymentMethod = value => {
    const { paymentMethodList } = this.state;
    let selectedPaymentMethod = paymentMethodList.filter(i => i.id === value)[0];
    this.setState({
      paymentMethodType: selectedPaymentMethod.paymentMethodCategory
    });
  };

  onCancel = () => {
    this.props.close();
  };

  setPlanedAmount = () => {
    const { payInfoDetail } = this.state;
    this.props.form.setFieldsValue({ 'planedAmount': {planedAmount: payInfoDetail.planedAmount} });
  };

  onRefreshPayInfoDetail = value => {
    const { payInfoDetail } = this.state;
    console.log(value);
    this.setState({
      show: false,
      payInfoDetail: Object.assign({}, payInfoDetail, { ...value })
    }, this.setPlanedAmount)
  };

  formatBankNumber = value => {
    if(typeof value !== 'string') return value;
    return value.replace(/(^\d{4})(\d+)(\d{4}$)/, (target, $1, $2, $3) => {return $1 + $2.replace(/./g, '*') + $3})
  };

  refreshBankOptions = (bankListOption, resetFields) => {
    this.setState({ bankListOption: bankListOption }, () => {
      this.props.form.setFieldsValue(resetFields);
    });
  };

  render() {
    const {loading, payInfoDetail, editMode, bankListOption, prePaymentList, paymentMethodList,
      contractLineId, contract, vendorInfo
    } = this.state;
    const { operateMode, hasSupplierSetting, expenseInfo, entry, customFormPropertyMap,
      isAuditEditable } = this.props;
    const { getFieldDecorator } = this.props.form;
    let editing = operateMode === 'CREATE' || (expenseInfo.status === 1001) || (isAuditEditable && editMode);
    let renderForm = i => (
      <div className='form-control'>
        <div className='form-label'>{PayInfoCustomFields(this)[i].label}</div>
        <div className='form-value'>{PayInfoCustomFields(this)[i].value(payInfoDetail, expenseInfo, paymentMethodList)}</div>
      </div>
    );
    return (
      <div className="pay-info-detail pay-with-no-invoice">
        <If value={isAuditEditable && !editMode}>
          <a onClick={() => this.setState({ editMode: true })} className='edit-btn'>
            <Icon type="form" /> {messages('common.edit')/*编辑*/}
          </a>
        </If>
        <Spin spinning={loading}>
          <Form className="new-form">
            {editing ? (
              <div>
                <h3 className='sub-title' style={{marginTop: 0}}>{messages('finance-9.key61')/*收款方信息*/}</h3>
                <FormItem label={messages('finance-9.key10')/*收款方账号*/}>
                  {getFieldDecorator('accountNumber', {
                    initialValue: payInfoDetail.payeeAccountNumber,
                    rules: [{
                      required: true,
                      message: messages('common.please.select'),
                    }]
                  })(
                    <Select
                      className="edit-pay-info__select"
                      getPopupContainer={triggerNode => triggerNode.parentNode}
                      onChange={this.onChangeBankAccount}
                      placeholder={messages('common.please.select')}
                    >
                      {bankListOption.map(item => (
                        <Option
                          key={item.bankAccount}
                          style={{whiteSpace: 'normal'}}
                          title={`${item.bankAccount} ${item.bankName}`}
                        >
                          {this.formatBankNumber(item.bankAccount)} {item.bankName}
                        </Option>
                      ))}
                    </Select>
                  )}

                  <AddBankAccount
                    vendorInfo={vendorInfo}
                    expenseInfo={expenseInfo}
                    isAuditEditable={isAuditEditable}
                    hasSupplierSetting={hasSupplierSetting}
                    bankListOption={bankListOption}
                    refreshBankOptions={this.refreshBankOptions}
                  />
                </FormItem>
                <FormItem label={messages('finance-9.key11')/*收款方户名*/}>
                  {getFieldDecorator('accountName', {
                    initialValue: payInfoDetail.payeeAccountName,
                    rules: [{
                      required: true,
                      message: messages('common.please.input'),
                    }]
                  })(
                    <Input disabled={true} placeholder={messages('common.please.input')}/>
                  )}
                </FormItem>
                <h3 className='sub-title'>
                  <span className='form-title-label'>{messages('finance-9.key26')/*付款信息*/}</span>
                </h3>
                <FormItem label={messages('finance-9.key15')/*预付类型*/}>
                  {getFieldDecorator('prepaymentTypeId', {
                    initialValue: payInfoDetail.prepaymentTypeId,
                    rules: [{
                      required: true,
                      message: messages('common.please.select'),
                    }]
                  })(
                    <Select
                      key='id'
                      getPopupContainer={triggerNode => triggerNode.parentNode}
                      placeholder={messages('common.please.select')}
                    >
                      {prePaymentList.map(item => (
                        <Option key={item.id}>
                          {item.prepaymentTypeName}
                        </Option>
                      ))}
                    </Select>
                  )}
                </FormItem>
                {expenseInfo.contractHeaderId &&
                  <FormItem
                    label={messages('finance-9.key16')/*关联合同行*/}
                  >
                    {getFieldDecorator('contractAssociatedDTOList', {
                      initialValue: payInfoDetail.contractAssociatedDTOList || [],
                      rules: [{
                        required: true,
                        message: messages('common.name.is.required', { arg1: messages('finance-9.key16')/*关联合同行*/ })
                      }]
                    })(
                      contractLineId ? (
                        <AssociateContract
                          contract={contract || []}
                          editable={editing}
                          expenseInfo={expenseInfo}
                          onRefreshPayInfoDetail={value => this.onRefreshPayInfoDetail(value)}
                        />
                      ) : (
                        <Chooser
                          type="choose_contract"
                          listExtraParams={{
                            documentType: 'PUBLIC_REPORT',
                            companyOID: expenseInfo.docCompanyOID,
                            currency: expenseInfo.currencyCode,
                            contractHeaderId: expenseInfo.contractHeaderId,
                            applicantDepartmentOID: expenseInfo.applicantDepartmentOID,
                            partnerCategory: 'VENDOR',
                            corporateFlag: true
                          }}
                          disabled={
                            (!expenseInfo.contractHeaderId && expenseInfo.contractPosition === 'DOCUMENTS_HEAD') ||
                            entry === 'audit'
                          }
                          labelKey="contractNumber"
                          valueKey="contractLineId"
                          itemMap
                          onChange={this.onChangeContractLine}
                        />)
                    )}
                  </FormItem>
                }
                <FormItem
                  label={messages('finance-9.key17')/*本次支付金额*/}
                >
                  {getFieldDecorator('planedAmount', {
                    initialValue: { planedAmount: payInfoDetail.amount || 0},
                    rules: [{
                      required: true
                    }]
                  })(
                    <WrapFormItem>
                      {(onChange, value) => (
                        <Row gutter={10}>
                          <Col span={12}>
                            <Select
                              disabled
                              value={expenseInfo.currencyCode}
                              placeholder='请选择'
                            >
                              <Option key={expenseInfo.currencyCode}>
                                {expenseInfo.currencyCode + ' ' + expenseInfo.currencyCodeName}
                              </Option>
                            </Select>
                          </Col>
                          <Col span={12}>
                            <InputNumber
                              onChange={amount => onChange({planedAmount: amount})}
                              value={value.planedAmount || 0}
                              disabled={payInfoDetail.contractAssociatedDTOList && payInfoDetail.contractAssociatedDTOList.length}
                            />
                          </Col>
                        </Row>
                      )}
                    </WrapFormItem>
                  )}
                </FormItem>
                <FormItem label={messages('finance-9.key18')/*付款方式*/}>
                  {getFieldDecorator('paymentMethodId', {
                    initialValue: payInfoDetail.paymentMethodId || customFormPropertyMap['payment.method'],
                    rules: [{
                      required: true,
                      message: messages('common.please.select'),
                    }]
                  })(
                    <Select
                      getPopupContainer={triggerNode => triggerNode.parentNode}
                      placeholder={messages('common.please.select')}
                      key={'paymentMethod'}
                      onChange={this.onChangePaymentMethod}
                    >
                      {paymentMethodList.map(item => {
                        return <Option key={item.id}>{item.description}</Option>
                      })}
                    </Select>
                  )}
                </FormItem>
                <FormItem label={messages('finance-9.key19')/*计划付款日期*/}>
                  {getFieldDecorator('planedPaymentDate', {
                    initialValue: payInfoDetail.planedPaymentDate ? moment(payInfoDetail.planedPaymentDate) : null,
                    rules: [{
                      required: true,
                      message: messages('common.please.select'),
                    }]
                  })(
                    <DatePicker
                      disabledDate={date => date && date.valueOf() < moment().subtract(1, 'days').valueOf()}
                    />
                  )}
                </FormItem>
                <FormItem label={messages('common.remark')/*备注*/}>
                  {getFieldDecorator('remark', {
                    initialValue: payInfoDetail.remark
                  })(
                    <TextArea placeholder={messages('common.please.select')} />
                  )}
                </FormItem>
              </div>
            ) : (
              <div>
                <h3 className='sub-title' style={{marginTop: 0}}>{messages('finance-9.key61')/*收款方信息*/}</h3>
                {['payeeAccountNumber', 'payeeAccountName'].map(i => renderForm(i))}
                <h3 className='sub-title'>{messages('finance-9.key26')/*付款信息*/}</h3>
                {['prepaymentTypeCode', expenseInfo.contractHeaderId && 'contractAssociatedDTOList', 'planedAmount', 'paymentMethod', 'planedPaymentDate', 'remark']
                  .filter(i => !!i)
                  .map(i => renderForm(i))}
              </div>
            )}
          </Form>
        </Spin>
        <div className="slide-footer">
          {editing && (
            <Button type="primary" onClick={this.handleSubmit} loading={loading}>
              {messages("common.save")}
            </Button>)}
          <Button onClick={this.onCancel}>{messages("common.cancel")}</Button>
        </div>
      </div>
    )
  }
}

PayWithInvoice.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    language: state.main.language,
    company: state.login.company,
    user: state.login.user,
    authPolicyAll: state.main.authPolicyAll,
    options: state.login.options,
    profile: state.login.profile,
    tenant: state.login.tenant,
  }
}

const WrappedPayWithInvoice = Form.create()(PayWithInvoice);

export default connect(mapStateToProps)(WrappedPayWithInvoice);
